'use strict'

import {app, BrowserWindow, screen, Tray, Menu, ipcMain, nativeImage} from 'electron'
import store from '../renderer/store.js'

store.dispatch('initProgram')
const appId = require('../../package').build.appId
app.setAppUserModelId(appId)
/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
let chatboxWindow
let setWindow
let screenshotWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}`

function createMainWindow () {
  let primaryDisplay = screen.getPrimaryDisplay()
  let workAreaSize = primaryDisplay.workAreaSize

  let x = workAreaSize.width - 300 - 200
  let y = (workAreaSize.height - 700) / 2

  mainWindow = new BrowserWindow({
    x,
    y,
    minWidth: 300,
    minHeight: 550,
    width: 300,
    height: 700,
    frame: false,
    useContentSize: true,
    skipTaskbar: true,
    webPreferences: {
      nodeIntegration: true
    }
  })

  mainWindow.webContents.openDevTools({mode: 'detach'})

  mainWindow.loadURL(`${winURL}/index.html`)

  mainWindow.on('closed', () => {
    app.exit()
  })
}

function createChatWindow () {
  chatboxWindow = new BrowserWindow({
    width: 500,
    height: 500,
    minWidth: 500,
    minHeight: 500,
    useContentSize: true,
    show: false,
    frame: false,
    webPreferences: {
      nodeIntegration: true
    }
  })
  chatboxWindow.loadURL(`${winURL}/chatbox.html`)

  chatboxWindow.webContents.openDevTools({mode: 'detach'})

  chatboxWindow.on('close', (ev) => {
    ev.preventDefault()
    // chatboxWindow.hide()
    chatboxWindow.webContents.send('clearSession')
  })

  chatboxWindow.on('show', () => {
    chatboxWindow.center()
  })
}

function createSetWindow () {
  setWindow = new BrowserWindow({
    width: 720,
    height: 520,
    resizable: false,
    useContentSize: true,
    show: false,
    frame: false,
    webPreferences: {
      nodeIntegration: true
    }
  })
  setWindow.loadURL(`${winURL}/set.html`)
  setWindow.on('close', (ev) => {
    ev.preventDefault()
    // setWindow.hide()
    setWindow.webContents.send('hideSetWindow')
  })

  setWindow.webContents.openDevTools({mode: 'detach'})
}

function createScreenshotWindow () {
  let screenSize = {width: 0, height: 0}
  screen.getAllDisplays().map((display, index) => {
    screenSize.width = Math.max(screenSize.width, display.bounds.x + display.bounds.width)
    screenSize.height = Math.max(screenSize.height, display.bounds.y + display.bounds.height)
  })
  screenshotWindow = new BrowserWindow({
    x: 0,
    y: 0,
    frame: false,
    show: false,
    skipTaskbar: true,
    alwaysOnTop: true,
    transparent: true
  })
  screenshotWindow.setPosition(0, 0)
}

ipcMain.on('setChatBoxWindowIcon', (ev, arg) => {
  chatboxWindow.setIcon(nativeImage.createFromDataURL(arg))
})

app.on('ready', () => {
  createMainWindow()
  createChatWindow()
  createSetWindow()
  createScreenshotWindow()
  createTray()
})

let tray = null

let trayShow = true

let trayImage = nativeImage.createFromDataURL(require('../renderer/assets/trayIcon.png'))

let interval = null
ipcMain.on('openUnread', (ev, arg) => {
  clearInterval(interval)
  if (arg) {
    interval = setInterval(changeTray, 500)
  } else {
    trayShow = true
    tray.setImage(trayImage)
  }
})

function changeTray () {
  if (trayShow) {
    tray.setImage(nativeImage.createEmpty())
    trayShow = false
  } else {
    tray.setImage(trayImage)
    trayShow = true
  }
}

function createTray () {
  tray = new Tray(trayImage)
  tray.on('click', handleTrayClick)
  const contextMenu = Menu.buildFromTemplate([
    {label: 'Item1', type: 'normal'},
    {label: 'Item2', type: 'normal'},
    {label: 'Item3', type: 'normal'},
    {
      click: handleTrayContextMenuItemClick,
      label: '退出',
      type: 'normal',
      id: 'close'
    }
  ])
  // tray.setToolTip('This is my application.')
  tray.setContextMenu(contextMenu)
}

function handleTrayClick (event, bounds, position) {
  mainWindow.show()
  mainWindow.focus()
}

function handleTrayContextMenuItemClick (menuItem, browserWindow, event) {
  switch (menuItem.id) {
    case 'close':
      app.exit()
      break
  }
}

app.on('window-all-closed', () => {
  console.log('window-all-closed')
  // if (process.platform !== 'darwin') {
  app.exit()
  // }
})

app.on('activate', () => {
  console.log('activate')
  if (mainWindow === null) {
    createMainWindow()
  }
})
app.on('quit', () => {
  console.log('quit')
  app.exit()
})
app.on('will-quit', () => {
  console.log('will-quit')
  app.exit()
})
app.on('before-quit', () => {
  console.log('before-quit')
  app.exit()
})

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
